package mypicture;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class MyPicture extends JPanel {
    BufferedImage image;
    public MyPicture(){
        //图片只需要加载一次，放在paintComponent中会被反复执行，所以应该把他放到构造方法中，只需加载一次
        File file = new File("Java-swing\\data\\1.jpg");
        try {
            System.out.println("加载图片");
            this.image= ImageIO.read(file);
            //g.drawImage(image,x,y,width,height,observer)
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        //设置背景
        int width = getWidth();
        int height = getHeight();
        g.setColor(Color.WHITE);
        g.fillRect(0,0,width,height);

//        File file = new File("Java-swing\\data\\1.jpg");
//        try {
//            BufferedImage image= ImageIO.read(file);
//            //g.drawImage(image,x,y,width,height,observer)
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        int imgW = image.getWidth();
        int imgH = image.getHeight();
        System.out.println(width+" "+height+" "+imgW+" "+imgH);
        System.out.println("======================");


        int fitW =width;
        int fitH= width*imgH/imgW;
        if(fitH>height){
            System.out.println("...");
            fitH = height;
            fitW = height*imgW/imgH;
        }
        System.out.println(width+" "+height+" "+imgW+" "+imgH+" "+fitW+" "+fitH);

        int fitX = (width - fitW)/2;
        int fitY = (height- fitH)/2;
        g.drawImage(image,fitX,fitY,fitW,fitH,null);
    }
}
